import axios from "axios";
import router from "@/router.js";
import { ElMessage } from "element-plus";

// 创建服务对象
const service = axios.create({
  timeout: 3600000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (sessionStorage.token) {
      config.headers.token = sessionStorage.token;
    }
    // 简化去除加载样式的处理
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 登录失效时跳转到登录页
    if (response.data.code === 999999) {
      router.replace("/login");
    }
    return response;
  },
  (error) => {
    const msg = error.response?.data?.msg || "请求失败";
    ElMessage({
      message: msg,
      type: "error",
    });
    return Promise.reject(error);
  }
);

export default service;
